import Vue from "vue";
import Vuex from "vuex";
import createPersistedState from "vuex-persistedstate";

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    user: {},
    token: "",
    isLogin: false,
  },
  getters: {
    getUser(state) {
      return state.user;
    },
    getToken(state) {
      return state.token;
    },
    getIsLogin(state) {
      return state.isLogin;
    },
  },
  mutations: {
    setUser(state, user) {
      state.user = user;
    },
    setToken(state, token) {
      state.token = token;
    },
    setIsLogin(state, isLogin) {
      state.isLogin = isLogin;
    },
    resetState(state) {
      // 新增：重置状态的mutation
      state.user = {};
      state.token = "";
      state.isLogin = false;
    },
  },
  actions: {
    setUser({ commit }, user) {
      commit("setUser", user);
    },
    setToken({ commit }, token) {
      commit("setToken", token);
    },
    setIsLogin({ commit }, isLogin) {
      commit("setIsLogin", isLogin);
    },
    logout({ commit }) {
      commit("resetState"); // 触发状态重置
    },
  },
  modules: {},
  plugins: [
    createPersistedState({
      key: "my_blog_store",
      paths: ["token", "user", "isLogin"], // 已包含 userInfo，持久化生效
    }),
  ],
});
